package dyyx;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

public class Demo1 {

	public static void main(String[] args) throws Exception {

		initFlowRules();
		
		for(int i=0;i<7;i++) {
			 run();
			 Thread.sleep(2000);
		}
	    
	}
	
	private static void run() throws Exception{
		long start = System.currentTimeMillis();
        int pass = 0;
        int blocked = 0;
		long time = 0;
	    while (true) {
	        // try-with-resources  自动 exit entry
	        try (Entry entry = SphU.entry("hello")) {
	            // System.out.println("hello world,"+LocalDateTime.now());
	            pass++;
	        } catch (BlockException ex) {
	            // 被流控的
	            // System.out.println("blocked!"+LocalDateTime.now());
	            blocked++;
	        }
	        time = System.currentTimeMillis() - start;
	        if( time>=1000) {
	        	break;
	        }
	    	Thread.sleep(20);
	    }
	    
	    System.out.println("pass="+pass+",blocked="+blocked+",time="+time);
	}
	
	
	private static void initFlowRules(){
	    List<FlowRule> rules = new ArrayList<>(); 
	    FlowRule rule = new FlowRule(); 
	    rule.setResource("hello"); 
	    // FLOW_GRADE_QPS FLOW_GRADE_THREAD
	    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
	    // qps 20
	    rule.setCount(20);  
	    rules.add(rule); 
	    FlowRuleManager.loadRules(rules); 
	}
}
